﻿package com.thorqq.magictimer;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.thorqq.magictimer.timeLoop.TLoopPolicyWeek;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

public class AdapterWeek extends BaseAdapter {

	public final class ViewHolder{
		TextView text;
		LinearLayout layout;
		
		TLoopPolicyWeek policy;
	}

    private LayoutInflater mInflater;
	private List<Map<String, Object>> mData;
	@SuppressWarnings("unused")
    private Context mContext;

	public AdapterWeek(Context context)
	{
		mInflater = LayoutInflater.from(context);
		mData = new ArrayList<Map<String, Object>>();
		mContext = context;
	}

	public AdapterWeek(Context context, List<Map<String, Object>> data)
	{
		mInflater = LayoutInflater.from(context);
		mData = data;
        mContext = context;
	}

	public void add(Map<String, Object> map)
	{
		mData.add(map);
	}
	
	public void updateItem(int position, String key, Object obj)
	{
		if (position < mData.size())
		{  
            mData.get(position).put(key, obj);  
        } 
	}

	public int getCount() {
		return mData.size();
	}

	public Object getItem(int position) {
		if (position < mData.size())
		{  
            return mData.get(position);  
        } 
		else  
        {
            return null;  
        }
	}

	public long getItemId(int position) {
		if (position < mData.size())
		{  
            return position;  
        } 
		else  
        {
            return -1;  
        }
	}

	public View getView(final int position, View convertView, ViewGroup parent) 
	{
		ViewHolder holder = null;
		

		if (convertView == null) 
		{
			holder = new ViewHolder();  
			
			//布局
			convertView = mInflater.inflate(R.layout.week_item, null);
            holder.text = (TextView) convertView.findViewById(R.id.WeekItemText);
            holder.layout = (LinearLayout) convertView.findViewById(R.id.WeekItemLayout);
            
            OnClickListener lst = (OnClickListener)mData.get(position).get("listener");
            holder.layout.setOnClickListener(lst);
            
			convertView.setTag(holder);
		}
		else 
		{
			holder = (ViewHolder)convertView.getTag();
		}

		holder.text.setText((String) mData.get(position).get("text"));
        holder.policy = (TLoopPolicyWeek)mData.get(position).get("policy");
        char[] daymask = holder.policy.getDayMask();
        
        if(daymask[position] == '1')
        {
            holder.layout.setBackgroundResource(R.drawable.week_pressed);
        }
        else
        {
            holder.layout.setBackgroundResource(R.drawable.transparent);
        }

		return convertView;
	}
}
